package com.tambapps.p2p.fandem.handshake

import com.tambapps.p2p.fandem.Fandem
import com.tambapps.p2p.speer.exception.HandshakeFailException
import com.tambapps.p2p.speer.handshake.SerializedHandshake
import java.io.DataInputStream
import java.io.DataOutputStream
import java.io.IOException

class FandemSenderHandshake(data: SenderHandshakeData?) :
    SerializedHandshake<SenderHandshakeData, ReceiverHandshakeData>(
        Fandem.serializer(), Fandem.deserializer(
            ReceiverHandshakeData::class.java
        ), data
    ) {
    @Throws(IOException::class)
    override fun apply(
        outputStream: DataOutputStream,
        inputStream: DataInputStream
    ): ReceiverHandshakeData {
        outputStream.writeUTF("FANDEM")
        outputStream.writeUTF(Fandem.VERSION)
        if (inputStream.readUTF() != "FANDEM") {
            throw HandshakeFailException("Remote peer is not a fandem peer")
        }
        val version = inputStream.readUTF()
        Fandem.checkVersionCompatibility(version)
        val receiverData = deserializer.deserialize(inputStream)!!
        validate(receiverData)
        serializer.serialize(data, outputStream)
        return receiverData
    }

    @Throws(HandshakeFailException::class)
    override fun validate(receiverHandshakeData: ReceiverHandshakeData?) {
    }
}
